package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.entity.Page;
import com.qf.entity.Result;
import com.qf.entity.ResultStatus;
import com.qf.entity.User;
import com.qf.service.UserService;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    //      page 代表页码  limit代表查询的条数
    @GetMapping("/users")
    public Result test1(@RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "limit", defaultValue = "3") Integer limit) {

        PageInfo<User> pageInfo = userService.findAll(page, limit);
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setCount(pageInfo.getTotal());
        result.setData(pageInfo.getList());
        return result;
    }

    @DeleteMapping("/users/{id}")
    public ResultStatus delete(@PathVariable Integer id) {
        int i = userService.deleteUsers(id);
        ResultStatus resultStatus = new ResultStatus();
        if (i > 0) {
            resultStatus.setStatus(true);
            resultStatus.setMessage("成功");
        } else {
            resultStatus.setStatus(false);
            resultStatus.setMessage("失败");
        }
        return resultStatus;
    }

    @PutMapping("/users")
    public ResultStatus update(User user) {
        int i = userService.update(user);
        ResultStatus resultStatus = new ResultStatus();
        if (i > 0) {
            resultStatus.setStatus(true);
            resultStatus.setMessage("修改成功");
        } else {
            resultStatus.setStatus(false);
            resultStatus.setMessage("修改失败");
        }
        return resultStatus;
    }

    @PostMapping("/users")
    public ResultStatus insert(User user) {
        int i = userService.insertUser(user);
        ResultStatus resultStatus = new ResultStatus();
        if (i > 0) {
            resultStatus.setStatus(true);
            resultStatus.setMessage("添加成功");
        } else {
            resultStatus.setStatus(false);
            resultStatus.setMessage("添加失败");
        }
        return resultStatus;
    }

    @GetMapping("/users/{id}")
    public ModelAndView find(@PathVariable Integer id, ModelAndView modelAndView) {
        System.out.println(id + "查询单个");
        User user = userService.find(id);
        ModelAndView modelAndView1 = new ModelAndView();
        modelAndView.addObject("user", "user");
        modelAndView.setViewName("forward:/update.jsp");

        return modelAndView;
    }

}
